package com.ruoyi.food.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.xbill.DNS.Address;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.AjaxResult.Type;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.food.object.TAttach;
import com.ruoyi.food.object.TEnterprise;
import com.ruoyi.food.object.TRedBlack;
import com.ruoyi.food.service.TAttachService;
import com.ruoyi.food.service.TEnterpriseService;
import com.ruoyi.food.util.AnalysisMultipartFileUtil;
import com.ruoyi.food.util.CodeUtil;
import com.ruoyi.food.util.RedisUtil;
import com.ruoyi.food.util.UploadUtil;
import com.wf.captcha.SpecCaptcha;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 餐饮企业controller
 * 
 * @author mengcc
 *
 */
@Controller
@Api(value = "TEnterpriseController", tags = "餐饮企业controller")
@RequestMapping("/enterprise")
public class TEnterpriseController extends BaseController {

	@Autowired
	private TEnterpriseService tEnterpriseService;

	@Autowired
	private TAttachService tAttachService;
	
	@Autowired
	private RedisUtil redisUtil;

	/**
	 * 文件存放绝对路径
	 */
	@Value("${upload.filepath}")
	private String filePath;

	/**
	 * 文件压缩存放路径
	 */
	@Value("${upload.presspath}")
	private String presspath;

	@Value("${file.upload.path.relative}")
	private String fileRelativePath;

	private String prefix = "page/enterprise";

	/**
	 * 进入餐饮页面
	 * 
	 * @return
	 */
	@GetMapping()
	public String enterprise() {
		return "page/enterprise";
	}

	@PostMapping("/list")
	@ApiOperation("查询餐饮企业列表")
	@ResponseBody
	public TableDataInfo findEnterprise(TEnterprise tEnterprise) {
		startPage();
		List<TEnterprise> list = tEnterpriseService.findTEnterprise(tEnterprise);
		return getDataTable(list);
	}

	// @PostMapping("/listByIsWaterPoint")
	@GetMapping("/listByIsWaterPoint")
	@ApiOperation("通过设置取水地点(IS_WATER_POINT)查询餐饮企业列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "isWaterPoint", value = "取水地点(0-未设置取水地点，1-已设置取水地点，3-查全部)", dataType = "int"),
			@ApiImplicitParam(name = "name", value = "餐饮企业名字", dataType = "String") })
	@ResponseBody
	public List<TEnterprise> findTenterpriseByisWP(@RequestParam int isWaterPoint,
			@RequestParam(defaultValue = "", required = false) String name) {
		List<TEnterprise> tEnterprises = tEnterpriseService.findTenterpriseByisWP(isWaterPoint, name);
		for (TEnterprise tEnterprise : tEnterprises) {
			List<TAttach> tAttachs = tAttachService.findTAttachByFK(tEnterprise.getEnterpriseId(), "t_enterprise");
			tEnterprise.setAttachs(tAttachs);
		}
		return tEnterprises;
	}

	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	@ApiOperation(value = "保存餐饮企业", notes = "")
	@ApiParam(name = "tEnterprise", value = "餐饮企业对象", required = true, type = "TEnterprise")
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult save(TEnterprise tEnterprise) {
		tEnterprise.setCreateTime(new Timestamp(System.currentTimeMillis()));
		if (tEnterprise.getName() == null || tEnterprise.getName().equals("")) {
			return new AjaxResult(Type.ERROR, "餐饮企业名字不能为空");
		} else if (tEnterprise.getSign() == null || tEnterprise.getSign().equals("")) {
			return new AjaxResult(Type.ERROR, "店名不能为空");
		} else if (tEnterprise.getType() == null || tEnterprise.getType().equals("")) {
			return new AjaxResult(Type.ERROR, "餐饮企业类型不能为空");
		} else if (tEnterprise.getWorkerNum() == 0) {
			return new AjaxResult(Type.ERROR, "从业人数不能为0");
		} else if (tEnterprise.getAddress() == null || tEnterprise.getAddress().equals("")) {
			return new AjaxResult(Type.ERROR, "餐饮企业地址不能为空");
		} else if (tEnterprise.getFzrName() == null || tEnterprise.getFzrName().equals("")) {
			return new AjaxResult(Type.ERROR, "负责人名字不能为空");
		} else if (tEnterprise.getFzrTel() == null || tEnterprise.getFzrTel().equals("")) {
			return new AjaxResult(Type.ERROR, "负责人电话不能为空");
		} /*
			 * else if (tEnterprise.getArea().compareTo(BigDecimal.ZERO) == 0) { return new
			 * AjaxResult(Type.ERROR, "营业面积不能为0"); } else if (tEnterprise.getCapacity() ==
			 * 0) { return new AjaxResult(Type.ERROR, "可容乃人数不能为0"); }
			 */
		return toAjax(tEnterpriseService.saveTEnterprise(tEnterprise));
	}

	@GetMapping("/update/{enterpriseId}")
	public String update(@PathVariable("enterpriseId") Long enterpriseId, ModelMap mmap) {
		mmap.put("enterprise", tEnterpriseService.findTenterpriseById(enterpriseId));
		return prefix + "/update";
	}

	/**
	 * 修改餐饮企业
	 * 
	 * @param tRedBlack
	 * @return
	 */
	@ApiOperation(value = "修改餐饮企业", notes = "")
	@ApiParam(name = "tEnterprise", value = "餐饮企业", required = true, type = "TEnterprise")
	@PostMapping("/update")
	@ResponseBody
	public AjaxResult updateRedEnterprise(@Validated TEnterprise tEnterprise) {
		return toAjax(tEnterpriseService.updateTEnterprise(tEnterprise));

	}

	@ApiOperation(value = "删除餐饮企业", notes = "")
	@ApiParam(name = "ids", value = "餐饮企业id", required = true, type = "Long")
	@PostMapping("/delete")
	@ResponseBody
	public AjaxResult deleteEnterprise(Long ids) {
		return toAjax(tEnterpriseService.deleteTenterprise(ids));
	}

	@GetMapping("/login")
	@ApiOperation("通过企业账号与密码登入")
	@ApiImplicitParams({ @ApiImplicitParam(name = "account", value = "账号", dataType = "String"),
			@ApiImplicitParam(name = "code", value = "验证码", dataType = "String"),
			@ApiImplicitParam(name = "password", value = "密码", dataType = "String") })
	@ResponseBody
	public AjaxResult login(HttpServletRequest request, @RequestParam String account, @RequestParam String password,
			@RequestParam String code) {
		String sessionCode = request.getSession().getAttribute("code").toString();
		if (code == null || !sessionCode.equals(code.trim().toLowerCase())) {
			request.getSession().removeAttribute("code");
			return new AjaxResult(Type.ERROR, "登入失败，请检查输入验证码是否正确");
		}
		List<TEnterprise> tEnterprises = tEnterpriseService.tEnterpriseLogin(account, password);
		if (!tEnterprises.isEmpty()) {
			request.getSession().removeAttribute("code");
			return new AjaxResult(Type.SUCCESS, "登入成功");
		} else {
			request.getSession().removeAttribute("code");
			return new AjaxResult(Type.ERROR, "登入失败，请检查登入账号和密码是否正确");
		}
	}

	@GetMapping("/getCode")
	@ApiOperation("获取验证码")
	//@ResponseBody
	public void getCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ServletOutputStream outputStream = response.getOutputStream();
		SpecCaptcha captcha = CodeUtil.getSpecCode();
		request.getSession().setAttribute("code", captcha.text().toLowerCase());
		captcha.out(outputStream);
		
		/*SpecCaptcha captcha = CodeUtil.getSpecCode();
        String verCode = captcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        // 存入redis并设置过期时间为30分钟
        redisUtil.set(key, verCode, 1800);
        // 将key和base64返回给前端
        return new AjaxResult().put("key", key).put("image", captcha.toBase64());*/
	}

	@PostMapping("/updateAcOrPs")
	@ApiOperation("修改账号与密码")
	@ApiImplicitParams({ @ApiImplicitParam(name = "newAccount", value = "新账号", dataType = "String"),
			@ApiImplicitParam(name = "newPassword", value = "新密码", dataType = "String"),
			@ApiImplicitParam(name = "account", value = "旧账号", dataType = "String"),
			@ApiImplicitParam(name = "password", value = "旧密码", dataType = "String") })
	@ResponseBody
	public AjaxResult update(@RequestParam String newAccount, @RequestParam String newPassword,
			@RequestParam String account, @RequestParam String password) {

		List<TEnterprise> tEnterprises = tEnterpriseService.tEnterpriseLogin(account, password);
		if (tEnterprises.isEmpty()) {
			return new AjaxResult(Type.ERROR, "修改失败，输入的旧账号和密码不正确");
		}
		tEnterpriseService.updateAcOrPs(newAccount, newPassword, account, password);
		return new AjaxResult(Type.SUCCESS, "修改成功");
	}

	@GetMapping("/upload/{enterpriseId}")
	public String upload(@PathVariable("enterpriseId") Long enterpriseId, ModelMap mmap) {

		TEnterprise tEnterprise = tEnterpriseService.findTenterpriseById(enterpriseId);
		List<TAttach> tAttachs = tAttachService.findTAttachByFK(tEnterprise.getEnterpriseId(), "t_enterprise");
		tEnterprise.setAttachs(tAttachs);
		mmap.put("enterprise", tEnterprise);
		return prefix + "/upload";
	}

	/**
	 * 文件上传
	 * 
	 * @param request
	 * @return
	 */
	@PostMapping("/upload")
	@ResponseBody
	public AjaxResult upload(HttpServletRequest request) {

		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;

		// 获取菜品图片
		List<MultipartFile> multipartFiles = multipartHttpServletRequest.getFiles("food");
		// 获取营业执照
		List<MultipartFile> licenseFiles = multipartHttpServletRequest.getFiles("license");
		// 获取餐厅环境图片
		List<MultipartFile> envFiles = multipartHttpServletRequest.getFiles("env");
		// 获取餐厅企业logo
		List<MultipartFile> logoFiles = multipartHttpServletRequest.getFiles("logo");
		// 获取餐厅企业视频
		List<MultipartFile> videoFiles = multipartHttpServletRequest.getFiles("video");

		// 获取企业id
		long enterpriseId = Long.parseLong(request.getParameter("enterpriseId"));

		if (multipartFiles.isEmpty() && licenseFiles.isEmpty() && envFiles.isEmpty() && logoFiles.isEmpty()
				&& videoFiles.isEmpty()) {
			return new AjaxResult(Type.ERROR, "上传文件不能为空");
		}

		List<TAttach> tAttachs = new ArrayList<TAttach>();
		if (!multipartFiles.isEmpty()) {
			tAttachs.addAll(UploadUtil.uploadByThum("t_enterprise_food", multipartFiles, enterpriseId, request,
					filePath, presspath));
		}
		if (!licenseFiles.isEmpty()) {
			tAttachs.addAll(UploadUtil.uploadByThum("t_enterprise_license", licenseFiles, enterpriseId, request,
					filePath, presspath));
		}
		if (!envFiles.isEmpty()) {
			tAttachs.addAll(
					UploadUtil.uploadByThum("t_enterprise_env", envFiles, enterpriseId, request, filePath, presspath));
		}

		if (!logoFiles.isEmpty()) {
			tAttachs.addAll(UploadUtil.uploadByThum("t_enterprise_logo", logoFiles, enterpriseId, request, filePath,
					presspath));
		}

		if (!videoFiles.isEmpty()) {
			tAttachs.addAll(UploadUtil.uploadVideo("t_enterprise_video", videoFiles, enterpriseId, request, filePath,
					presspath));
			// tAttachs.addAll(UploadUtil.upload("t_enterprise_video", videoFiles,
			// enterpriseId, request, filePath));

		}
		if (tAttachs.size() == 0) {
			return new AjaxResult(Type.ERROR, "上传失败");
		}

		tAttachService.save(tAttachs);

		return new AjaxResult(Type.SUCCESS, "上传成功");
	}

	@GetMapping("/details")
	@ApiOperation("查询餐饮企业详情(包含图片)")

	@ApiImplicitParam(name = "enterpriseId", value = "餐饮企业id", dataType = "long")

	@ResponseBody
	public TEnterprise findDetails(@RequestParam long enterpriseId) {
		TEnterprise tEnterprise = tEnterpriseService.findTenterpriseById(enterpriseId);

		List<TAttach> tAttachs = tAttachService.findTAttachByFK(tEnterprise.getEnterpriseId(), "t_enterprise");
		tEnterprise.setAttachs(tAttachs);

		return tEnterprise;
	}

	@GetMapping("/look/{enterpriseId}")
	public String look(@PathVariable("enterpriseId") Long enterpriseId, ModelMap mmap) {

		TEnterprise tEnterprise = tEnterpriseService.findTenterpriseById(enterpriseId);
		List<TAttach> tAttachs = tAttachService.findTAttachByFK(tEnterprise.getEnterpriseId(), "t_enterprise");
		tEnterprise.setAttachs(tAttachs);
		mmap.put("enterprise", tEnterprise);
		return prefix + "/look";
	}

	@GetMapping("/listBySignupSafe")
	@ApiOperation("通过报名放心餐饮(signupSafe)查询餐饮企业列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "signupSafe", value = "是否报名放心餐饮(0-否，1-是，3-查全部)", dataType = "int"),
			@ApiImplicitParam(name = "name", value = "餐饮企业名字(可为空，不传)", dataType = "String") })
	@ResponseBody
	public List<TEnterprise> findTenterpriseBySafe(@RequestParam int signupSafe,
			@RequestParam(defaultValue = "", required = false) String name) {
		List<TEnterprise> tEnterprises = tEnterpriseService.findTenterpriseBySafe(signupSafe, name);
		for (TEnterprise tEnterprise : tEnterprises) {
			List<TAttach> tAttachs = tAttachService.findTAttachByFK(tEnterprise.getEnterpriseId(), "t_enterprise");
			tEnterprise.setAttachs(tAttachs);
		}
		return tEnterprises;
	}

	@GetMapping("/listByContain")
	@ApiOperation("查询类型包含食堂的餐饮企业")
	@ResponseBody
	public List<TEnterprise> findTenterpriseByContainType() {
		List<TEnterprise> tEnterprises = tEnterpriseService.findTenterpriseByContainType("食堂");
		for (TEnterprise tEnterprise : tEnterprises) {
			List<TAttach> tAttachs = tAttachService.findTAttachByFK(tEnterprise.getEnterpriseId(), "t_enterprise");
			tEnterprise.setAttachs(tAttachs);
		}
		return tEnterprises;
	}

	@GetMapping("/listByNoContain")
	@ApiOperation("查询类型不包含食堂的餐饮企业")
	@ResponseBody
	public List<TEnterprise> findTenterpriseByNoContainType() {
		List<TEnterprise> tEnterprises = tEnterpriseService.findTenterpriseByNoContainType("食堂");
		for (TEnterprise tEnterprise : tEnterprises) {
			List<TAttach> tAttachs = tAttachService.findTAttachByFK(tEnterprise.getEnterpriseId(), "t_enterprise");
			tEnterprise.setAttachs(tAttachs);
		}
		return tEnterprises;
	}

	@GetMapping("/listByLike")
	@ApiOperation("通过店名和地址模糊查询")
	@ResponseBody
	public List<TEnterprise> findTenterpriseByLike(@RequestParam(defaultValue = "", required = false) String string) {
		List<TEnterprise> tEnterprises = tEnterpriseService.findTenterpriseByLike(string);
		for (TEnterprise tEnterprise : tEnterprises) {
			List<TAttach> tAttachs = tAttachService.findTAttachByFK(tEnterprise.getEnterpriseId(), "t_enterprise");
			tEnterprise.setAttachs(tAttachs);
		}
		return tEnterprises;
	}

	@GetMapping("/getNum")
	@ApiOperation("查询餐饮企业库存数")
	@ApiImplicitParam(name = "enterpriseId", value = "餐饮企业id", dataType = "long")
	@ResponseBody
	public long findNum(long enterpriseId) {
		TEnterprise tEnterprise = tEnterpriseService.findTenterpriseById(enterpriseId);
		return tEnterprise.getStockNum();
	}

}
